package com.mmg.cosplay.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mmg.cosplay.entity.dto.RolePresetRequestDTO;
import com.mmg.cosplay.entity.po.RolePreset;
import com.mmg.cosplay.mapper.RolePresetMapper;
import com.mmg.cosplay.service.IRolePresetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fly
 * @since 2025-09-22
 */
@Service
public class RolePresetServiceImpl extends ServiceImpl<RolePresetMapper, RolePreset> implements IRolePresetService {

    @Override
    public Page<RolePreset> listByDTO(RolePresetRequestDTO requestDTO) {
        // 设置默认分页参数
        Integer current = requestDTO.getStartPage() != null ? requestDTO.getStartPage() : 1;
        Integer size = requestDTO.getPageSize() != null ? requestDTO.getPageSize() : 10;
        
        // 创建分页对象
        Page<RolePreset> page = new Page<>(current, size);
        
        // 构建查询条件
        LambdaQueryWrapper<RolePreset> queryWrapper = new LambdaQueryWrapper<>();
        
        // 角色名称模糊查询
        queryWrapper.like(StringUtils.hasLength(requestDTO.getRoleName()), 
                         RolePreset::getRoleName, requestDTO.getRoleName());
        // 查询私有角色：isPrivate为0且createBy等于当前登录用户ID
        Long currentUserId = Long.parseLong(StpUtil.getLoginId().toString());
        // 根据isPrivate字段判断查询条件（0-私有，1-公开）
        if (requestDTO.getIsPrivate() != null) {
            if (requestDTO.getIsPrivate() == 0) {

                queryWrapper.eq(RolePreset::getCreateBy, currentUserId);
            } else {
                // 查询公开角色：isPrivate为1或者null的角色
                queryWrapper.and(wrapper -> wrapper.isNull(RolePreset::getIsPrivate)
                                                  .or()
                                                  .eq(RolePreset::getIsPrivate, 1)
                                                  .or()
                                                  .eq(RolePreset::getCreateBy, currentUserId)

                );
            }
        }
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc(RolePreset::getCreateTime);
        
        // 执行分页查询
        return this.page(page, queryWrapper);
    }
}
